import datetime
import logging
import requests
import yaml

from Hogwarts.Homeworks.hw0718.api.base import BaseAPI


class WeWork(BaseAPI):

    def __init__(self):
        self.base_url = 'https://qyapi.weixin.qq.com/cgi-bin'
        self.token_info = self._get_local_token_info()
        self.token = self.get_token()

    def get_token(self):
        """
        设置token属性
        如果本地token仍然有效则使用本地token；
        如果本地token失效则重新获取并更新。
        """
        now_timestamp = int(datetime.datetime.now().timestamp())
        expiry_deadline = self.token_info.get('expiry_deadline')

        if now_timestamp < expiry_deadline:
            expiry_remark = self.token_info.get('expiry_remark')
            logging.info(f"------ 正在使用本地token，失效时间：{expiry_remark} ------")
            token = self.token_info.get('token')
        else:
            logging.info("------ 本地token已失效------")
            token = self._get_new_token()
        return token


    @staticmethod
    def _get_local_token_info():
        logging.info("------ 读取本地token信息 ------")
        with open('../local/token.yaml', 'r', encoding='utf-8') as f:
            token_local = yaml.safe_load(f)
        return token_local

    def _get_new_token(self):
        logging.info("------ 请求新token ------")
        token_info = self._get_local_token_info()

        corp_id = token_info.get('ios_corp_id')
        corp_secret = token_info.get('ios_corp_secret')
        url = f"{self.base_url}/gettoken?corpid={corp_id}&corpsecret={corp_secret}"
        resp = requests.get(url).json()

        token = resp.get('access_token')  # 提取token

        logging.info("------ 更新token对象 ------")
        duration = resp.get('expires_in')  # 提取duration
        expiry_deadline = int(datetime.datetime.now().timestamp()) + duration  # 推算下一个失效时间戳
        expiry_remark = datetime.datetime.fromtimestamp(expiry_deadline).strftime('%Y-%m-%d %H:%M:%S')
        token_info.update({'token': token,
                           'duration': duration,
                           'expiry_deadline': expiry_deadline,
                           'expiry_remark': expiry_remark})

        logging.info("------ 保存新token到本地 ------")
        with open('../local/token.yaml', 'w', encoding='utf-8') as f:
            yaml.safe_dump(token_info, f)

        return token
